//
//  AppService.swift
//  SwiftuiZsa
//
//  Created by hccc on 2023/11/16.
//

import Foundation
import RxSwift
import MMKV

class AppService: BaseLogic {
    static let to = AppService()
    private override init() {}
    // MARK: - ----------------------------------info
    
    private var config: AppConfig = AppConfig()
    static var config: AppConfig { to.config }
    
    static var phoneImei: String {
        get {
            if let v = KVStore[.phoneImei] {
                return v 
            } else {
                let v = UUID().uuidString
                KVStore[.phoneImei] = v
                return v
            }
        }
        set {
            KVStore[.phoneImei] = newValue
        }
    }
    
    // MARK: - ----------------------------------action
    @MainActor func prepare() {
        // MMKV配置
        prepareMMKV()
    }
    
    func prepareMMKV() {
#if DEBUG
        MMKV.initialize(rootDir: nil, logLevel: .info)
#else
        MMKV.initialize(rootDir: nil, logLevel: .none)
#endif
    }
    
    func fetchConfig() -> Observable<Void> {
        AppAPI.config()
            .make()
            .unwrap(type: AppConfig.self)
            .do(onSuccess: {[weak self] config in
                guard let self = self else { return }
                self.config = config
            },onError: { error in
                
            })
            .map({ _ in () })
            .asObservable()
    }
}
